<template>
  <div ref="chartRef" :style="{ width, height }" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'

interface SeriesData {
  name: string
  data: number[]
  color?: string
}

interface Props {
  title?: string
  xAxisData: string[]
  yAxisName?: string
  data: number[] | SeriesData[]
  width?: string
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  yAxisName: '',
  width: '100%',
  height: '400px'
})

const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  // 先销毁之前的图表实例，避免内存泄漏
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  chartInstance = echarts.init(chartRef.value)

  // 判断是单条还是多条折线
  const isMultiLine = Array.isArray(props.data) && props.data.length > 0 && typeof props.data[0] === 'object'

  const series = isMultiLine
    ? (props.data as SeriesData[]).map(item => ({
      name: item.name,
      data: item.data,
      type: 'line',
      smooth: true,
      ...(item.color && { lineStyle: { color: item.color }, itemStyle: { color: item.color } })
    }))
    : [{
      data: props.data as number[],
      type: 'line',
      smooth: true
    }]

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: isMultiLine ? {
      data: (props.data as SeriesData[]).map(item => item.name),
      top: 10
    } : undefined,
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%',
      top: isMultiLine ? '20%' : '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.xAxisData
    },
    yAxis: {
      type: 'value',
      name: props.yAxisName
    },
    series
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  initChart()
})

watch(() => [props.xAxisData, props.data, props.title, props.yAxisName], () => {
  if (chartInstance) {
    chartInstance.clear()
    initChart()
  }
}, { deep: true })

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>